//
// Created by xili on 2024/7/30 8:01.
// Go big or go home.
//
#include <vector>

using namespace std;

class Solution {
public:
    int islandPerimeter(vector<vector<int>> &grid) {
        int ans = 0;
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j] == 1) {
                    ans += 4 - counts(grid, i, j);
                }
            }
        }
        return ans;
    }

    int counts(vector<vector<int>> &grid, int i, int j) {
        int cnts = 0;
        if (i - 1 >= 0 && grid[i - 1][j] == 1) {
            cnts++;
        }
        if (i + 1 < grid.size() && grid[i + 1][j] == 1) {
            cnts++;
        }
        if (j - 1 >= 0 && grid[i][j - 1] == 1) {
            cnts++;
        }
        if (j + 1 < grid[0].size() && grid[i][j + 1] == 1) {
            cnts++;
        }
        return cnts;
    }
};